package com.cby.library.tool.widget.floatedit

import android.app.Activity
import android.graphics.Rect
import android.util.Log
import android.view.View
import android.view.Window
import android.view.WindowManager
import android.widget.EditText
import android.widget.PopupWindow

class CbyFloatInput {

    private lateinit var inputWindow: CbyFloatInputWindow

    private var mNowHeight = 0
    private var mOldHeight = 0
    private var mScreenHeight = 0

    constructor(activity: Activity) {
        //initGlobal(activity)
        initInputWindow(activity)
    }


    private fun initGlobal(activity: Activity) {
        val decorView = activity.window.decorView
        val rootView =
            activity.findViewById<View>(Window.ID_ANDROID_CONTENT)
        decorView.viewTreeObserver.addOnGlobalLayoutListener {
            val r = Rect()
            activity.window.decorView.getWindowVisibleDisplayFrame(r)
            if (mScreenHeight == 0) {
                mScreenHeight = r.bottom
            }
            //这边针对其他的机器适配了，判断
            var navOffset = 0
            if (rootView != null) {
                navOffset = mScreenHeight - rootView.height
            }
            mNowHeight = mScreenHeight - r.bottom
            if (navOffset > 0) {
                mNowHeight -= navOffset
            }
            Log.i(
                "chenby",
                "mScreenHeight = $mScreenHeight,mNowh = $mNowHeight"
            )
            if (mOldHeight != -1 && mNowHeight != mOldHeight) {
                val mIsSoftKeyboardPop: Boolean = mNowHeight > 0
                if (mIsSoftKeyboardPop) {
                    // TODO: 2020/11/9 输入法弹出
                } else {
                    if (inputWindow != null) {
                        inputWindow.dismiss()
                    }
                    // TODO: 2020/11/9 输入法关闭
                }
            }
            mOldHeight = mNowHeight
        }
    }

    private fun initInputWindow(activity: Activity) {
        inputWindow = CbyFloatInputWindow(activity).apply {
            isFocusable = true
            inputMethodMode = PopupWindow.INPUT_METHOD_NEEDED
            softInputMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE
        }
    }

    fun show(anchorView: View?, targetEdit: EditText?) {
        if (inputWindow != null) {
            if (targetEdit != null) {
                inputWindow.setTargetEdit(targetEdit)
            }
            inputWindow.show(anchorView)
        }
    }
}